package com.ruoyi.web.cp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.web.cp.service.NumberChecker.SKIP_NUMBER2;

@Slf4j
@Service
public class LeyuCpService {
    private static final String ISSUE = "issue";
    private static final String MM = "mm";
    @Autowired
    private HttpService httpService;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;

//    @Async
    public void getLeyuCpList(String ticketId, String name, JSONObject cache) {
        getLeyuCpList(ticketId, name, cache, 1000);
    }

//    @Async
    public void getLeyuCpList(String ticketId, String name, JSONObject cache, Integer interval) {
        String cacheMM = (String) cache.getOrDefault(name + MM, "0");
        String mm = DateUtil.format(new Date(), MM);
        if (mm.equals(cacheMM)) {
            return;
        }
        if (((Integer.parseInt(cacheMM) * 1000 + interval) % 60000) > Integer.parseInt(mm) * 1000) {
            return;
        }
        JSONObject data = httpService.sendLeyuCpList(ticketId);
        JSONArray array;
        if ("0".equalsIgnoreCase(data.getString("code"))
                && CollUtil.isNotEmpty(array = data.getJSONArray("data"))) {
            data = array.getJSONObject(0);
            String issue = data.getString(ISSUE);
            if (issue.equals(cache.get(name + ISSUE))) {
                return;
            }
            cache.put(name + ISSUE, issue);
            cache.put(name + MM, mm);
            log.info("{}===>{},{}", name, issue, data.getString("code"));

            checkSameCodes(array, name, issue);
            isArithmeticSequence(data.getString("code"), name, issue, cache);
        }
    }

    public void checkSameCodes(JSONArray array, String name, String issue) {
        if (array == null || array.isEmpty()) {
            return;
        }
        List<String[]> datas = new ArrayList<>();
        List<String[]> datas2 = new ArrayList<>();
        for (int i = 0; i < SKIP_NUMBER2; i++) {
            if (i < 5) {
                datas.add(array.getJSONObject(i).getString("code").split(","));
            }
            datas2.add(array.getJSONObject(i).getString("code").split(","));
        }
        Map<String, Set<String>> map = new LinkedHashMap<>();
        for (int j = 0; j < 10; j++) {
            for (int i = 0; i < 5; i++) {
                String[] data = datas.get(i);
                Set<String> set = map.getOrDefault(j + "", new HashSet<>());
                set.add(data[j]);
                map.put(j + "", set);
            }
        }
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Set<String> set = map.get(key);
            if (set.size() == 1) {
                String msg = CharSequenceUtil.format("{},issue:{},{},{},连续同号", name, issue, key, set);
                log.info(msg);
                winxinService.sendTextMessage("1000015", msg);
            }
        }

        if (NumberChecker.isSkipNumbers(datas)) {
            String msg = CharSequenceUtil.format("{},issue:{},前4跳号", name, issue);
            log.info(msg);
            winxinService.sendTextMessage("1000009", msg);
        }
        if (NumberChecker.isSkipNumbers2(datas2)) {
            String msg = CharSequenceUtil.format("{},issue:{},连续跳号4", name, issue);
            log.info(msg);
            winxinService.sendTextMessage("1000015", msg);
        }
    }

    //增加方法，判断传入的以空格切割的10位数，前5位或前5位是否是递增或递减
    public void isArithmeticSequence(String code, String name, String issue, JSONObject cache) {
        String[] codes = code.split(",");
        boolean boo1 = NumberChecker.isIncreasing(codes, 0, 5);
        boolean boo2 = NumberChecker.isDecreasing(codes, 0, 5);
        boolean boo3 = NumberChecker.isIncreasing(codes, 0, 4);
        boolean boo4 = NumberChecker.isDecreasing(codes, 0, 4);
        List<String> msgs = new ArrayList<>();
        msgs.add(name);
        msgs.add(issue);
        msgs.add(code);
        if (boo1 || boo2) {
            msgs.add("前5递减&递增,上期:" + cache.getString(name + "5up"));
            cache.put(name + "5up", issue);
            writeToFile(name, issue);
        }
//        else if (boo3) {
//            msgs.add("前4递增,上期:" + cache.getString(name + "4up"));
//            cache.put(name + "4up", issue);
//        } else if (boo4) {
//            msgs.add("前4递减,上期:" + cache.getString(name + "4down"));
//            cache.put(name + "4down", issue);
//        }
        if (msgs.size() > 3) {
            log.info(CollUtil.join(msgs, "\n"));
            String msg = CollUtil.join(msgs, "\n");
            winxinService.sendTextMessage("1000016", msg);
        }
    }

    public void writeToFile(String name, String issue) {
        String path = configLoader.getRmPath() + "\\leyu\\" + name + "\\" + DateUtil.format(new Date(), "MMdd") + ".txt";
        FileUtil.writeLines(Arrays.asList(issue), path, "utf8", true);
    }
}
